<?php 
namespace app\admin\model;
use think\Model;
use think\Db;
class Goods_category extends Model
{
	protected $table = 'goods_category';
	public function getmenu($pid=null){
		 // 查询数据
		if(isset($pid)){
			$data = Db::name('goods_category')
            ->where("pid = $pid")
            ->select();
            $arr=$this::_get_cate_list($data); 
		}else{
			$data = Db::name('goods_category')->select();
			$arr=$this::_get_child($data); 
		}
        //得到菜单数组
        $json=json_encode($arr);//返回json格式
        return $arr; //这里直接返回了数组
    }
    public function getChildCate($pid){
        $data = Db::name('goods_category')->select();
        $arr=$this::_get_child($data,$pid);
        return $arr; 
    }
    //分类级别
    static protected function _cate_level($data, $pid=0, $level=0){
        $array = array();
        foreach ($data as $k => $v){
            if ($v['pid'] == $pid){
                $v['level'] = $level;
                $array[] = $v;
                unset($data[$k]);
                $array = array_merge($array, self::_cate_level($data, $v['id'],$level+1)); //递归
            }
        }
        return $array;
    } 
    //菜单
    static protected function _get_child($data, $pid=0){
        $array = array();
        foreach ($data as $k => $v){
            if ($v['pid'] == $pid){
                $v['child'] = self::_get_child($data, $v['id']); //递归
                $array[] = $v;
            }
        }
        return $array;
    }
    static protected function _get_cate_list($data, $pid=0){
    	$array = array();
        foreach ($data as $k => $v){
            if ($v['pid'] == $pid){
                $v['child'] = self::_get_child($data, $v['id']); //递归
                $array[] = $v;
            }else{
				$array[] = $v;
			}
        }
        return $array;
    }
    // 或者：
    static protected function _get_child_s($data, $pid=0){
        $array = [];
        foreach ($array as $v) {
            if($pid == $v['pid']){
                $v['child'] = $this->_get_child($data,$v['id']);
                $array[] = $v;
            }
        }
        return $array;
    }
}